package com.qfang.common.util;

import java.util.Calendar;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qfang.common.util.StringUtil;

public class CookieUtil {

	public static final String COOKIE_HISTORY_KEYWORDS = "historyKeywords";

	public static Cookie getCooie(HttpServletRequest request, String cookieName) {
		Cookie[] cookies = request.getCookies();
		Cookie ck = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookieName.equals(cookie.getName())) {
					ck = cookie;
					break;
				}
			}
		}
		return ck;
	}

	public static Cookie addCookie(HttpServletResponse resp, String cookieName, String cookieValue) {
		return addCookie(resp, cookieName, cookieValue, ".qfang.com");
	}

	public static Cookie addCookie(HttpServletResponse resp, String cookieName, String cookieValue, String domain) {
		cookieName = StringUtil.filterCRLFInjection(cookieName);
		cookieValue = StringUtil.filterCRLFInjection(cookieValue);
		Cookie ck = new Cookie(cookieName, cookieValue);
		ck.setMaxAge(14 * 24 * 3600);
		ck.setPath("/");
		if (domain != null) {
			ck.setDomain(domain);
		}
		resp.addCookie(ck);
		return ck;
	}

	public static Cookie addTodayCookie(HttpServletResponse resp, String cookieName, String cookieValue) {
		cookieName = StringUtil.filterCRLFInjection(cookieName);
		cookieValue = StringUtil.filterCRLFInjection(cookieValue);
		Cookie cookie = new Cookie(cookieName, cookieValue);
		Calendar now = Calendar.getInstance();
		Calendar calendar = Calendar.getInstance();
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
				23, 59, 59);
		int intValue = Long.valueOf((calendar.getTime().getTime() - now.getTime().getTime()) / 1000).intValue();
		cookie.setMaxAge(intValue);
		// System.out.println(intValue);
		cookie.setPath("/");
		resp.addCookie(cookie);
		return cookie;
	}

	

}
